import { defineStore } from 'pinia'
import { ref,computed } from 'vue'

export const useCartStore = defineStore('cart', () => {

	const cartItems=ref([]) // 购物车商品列表

	const addCartItem = (item) => {
		if (cartItems.value.length > 0) {
			const selectedCartItem = cartItems.value.find((cartItem) => {
				return cartItem.cd_id == item.cd_id
			});
			
			if (selectedCartItem) {
				selectedCartItem.num++;
			}else{
				cartItems.value.push({
					...item,
					num: 1
				})
			}
		} else {
			cartItems.value.push({
				...item,
				num: 1
			})
		}
		// console.log(333333,cartItems)

	}

	// 计算商品数量
	const getItemsCount = computed(() => {
		
		return cartItems.value.reduce((count, item) => count + item.num,
			0);
	});

	// 计算商品的总价格
	const getTotalPrice = computed(() => {
		return cartItems.value.reduce((total, item) => {
			const result = parseFloat(total) + parseFloat(item.cd_price) *parseFloat(item.num)
			return result.toFixed(2)
		}, 0);
	});

	// 清空购物车
	const clearCart = () => {
		cartItems.value = []
	}
	
	//删除数量小于0的商品
	const deleteCartItem = (itemId)=>{
		const selectedItemIndex = cartItems.value.findIndex((cartItem) => {
			return cartItem.cd_id == itemId
		});
		cartItems.value.splice(selectedItemIndex, 1);
	}

	// 通过+-来修改商品数量
	const changeItemQuantity = (item, quantity) => {
		const selectedCartItem = cartItems.value.find((cartItem) => {
			return cartItem.cd_id == item.cd_id
		});
		
		if (selectedCartItem) {
			selectedCartItem.num = quantity ;
		}
	}

	return {
		cartItems,
		deleteCartItem,
		addCartItem,
		getItemsCount,
		getTotalPrice,
		clearCart,
		changeItemQuantity,
	}
}
, {
	// 小程序端配置
	persist: {
		storage: {
			getItem(key) {
				return uni.getStorageSync(JSON.parse(key))
			},
			setItem(key, value) {
				uni.setStorageSync(key, JSON.stringify(value))
			}
		}
	}
},

);